package designPattern.structure7.Flyweight.chapter23_flyweight.test23_5;

import java.util.HashMap;

public class ElementFactory {
    static ElementFactory factory = new ElementFactory();
    private HashMap<String, Element> hashMap;

    private ElementFactory() {
        hashMap = new HashMap<String, Element>();
    }

    public static ElementFactory getFactory() {
        return factory;
    }

    public synchronized Element getElement(String key) {
        if (hashMap.containsKey(key))
            return hashMap.get(key);
        else {
            char elementOne = '\0', elementTwo = '\0';
            elementOne = key.charAt(0);
            elementTwo = key.charAt(1);
            Element element = new TwoElement(elementOne, elementTwo);
            hashMap.put(key, element);
            return element;
        }
    }

    class TwoElement implements Element {  // TwoElement是内部类
        char elementOne, elementTwo;

        private TwoElement(char elementOne, char elementTwo) {
            this.elementOne = elementOne;
            this.elementTwo = elementTwo;
        }

        public char getElementOne() {
            return elementOne;
        }

        public char getElementTwo() {
            return elementTwo;
        }

    }
} 
